import axios from 'axios'
import { useUserStore } from '@/store/user/index.js'
import { showToast } from 'vant'
import { storageDict } from '@/config/dict'

let _axios = null
let ignoreTokenErrorUntil = 0 // ✅ 防止切换账户瞬间触发登出

// ✅ 在切换账户时调用，用于临时屏蔽 token 失效登出
export function ignoreTokenError(ms = 4000) {
  ignoreTokenErrorUntil = Date.now() + ms
  console.log(`⏳ 临时忽略 Token 错误 ${ms}ms`)
}

// ====================== 初始化 ======================
export const baseURL = __config._BASE_API

if (!_axios) {
  _axios = axios.create({
    baseURL: baseURL,
    headers: {
      'Content-Type': 'application/json'
    },
    timeout: 60 * 1000
  })
}

// ====================== 请求拦截器 ======================
_axios.interceptors.request.use((config) => {
  const userStore = useUserStore()
  const token = userStore.token || localStorage.getItem(storageDict.TOKEN)

  if (token) {
    config.headers['authorization'] = token
    config.headers['satoken'] = token
  }

  const html = document.querySelector('html')
  if (html) {
    config.headers['language'] = html.getAttribute('language')
    config.headers['lang'] = html.getAttribute('lang')
  }

  return config
})

// ====================== 响应拦截器 ======================
_axios.interceptors.response.use(
  (response) => {
    const userStore = useUserStore()

    if (response.status === 200) {
      const { data } = response

      // ✅ 临时忽略切换账户期间的 token 失效提示
      if (
        data.code == '500' &&
        data?.msg?.toLowerCase()?.includes('token') &&
        (userStore._switching || Date.now() < ignoreTokenErrorUntil)
      ) {
        console.warn('⚠️ 忽略短期 Token 校验错误（切换账户中）')
        return Promise.resolve({ code: 1, msg: 'ignore token check' })
      }

      // ✅ 正常 token 失效处理
      if (data.code == '500' && data?.msg?.toLowerCase()?.includes('token')) {
        console.warn('⚠️ 检测到 Token 失效，执行登出')
        userStore.signOut()
        setTimeout(() => location.reload(), 50)
        return Promise.reject(response)
      }

      if (data && data.code > 0) {
        return Promise.resolve(data)
      } else {
        if (data.msg && data.code !== 200) showToast(data.msg)
        return Promise.reject(response)
      }
    } else {
      showToast('Network anomaly')
      return Promise.reject(response)
    }
  },
  (error) => {
    console.error('❌ Axios Error:', error)
    showToast('Network error, please try again later')
    return Promise.reject(error)
  }
)

// ====================== 封装请求方法 ======================
export const post = (url, params) => _axios.post(url, params)
export const get = (url, params) => _axios.get(url, { params })
export default _axios
